use crate::{core::error::AppError, utils::polkit};
use std::path::Path;
use tokio::process::Command;

pub struct FlatpakInstaller;

impl FlatpakInstaller {
    pub async fn install_bundle(&self, path: &str) -> Result<(), AppError> {
        let path = Path::new(path);
        if !path.exists() {
            return Err(AppError::FileOperation("文件不存在".into()));
        }
        
        polkit::check_authorization("org.deepin.flatpak.install").await?;
        
        // 验证运行时
        let runtime = self.extract_runtime(path).await?;
        if !self.is_runtime_installed(&runtime).await? {
            return Err(AppError::MissingDependency(runtime));
        }
        
        // 执行安装
        Command::new("flatpak")
            .args(&["install", "-y", "--bundle", path.to_str().unwrap()])
            .status()
            .await?;
            
        Ok(())
    }
    
    async fn extract_runtime(&self, path: &Path) -> Result<String, AppError> {
        let output = Command::new("flatpak")
            .args(&["build-bundle", "--info", path.to_str().unwrap()])
            .output()
            .await?;
            
        // 解析运行时信息
        Ok(String::from_utf8_lossy(&output.stdout)
            .lines()
            .find(|l| l.starts_with("Runtime:"))
            .map(|l| l.replace("Runtime:", "").trim().to_string())
            .unwrap_or_default())
    }
}